<?php
function aac($appname){
    global $db;
    $class = $appname;
    $path = THINKAPP.'/'.$appname.'/';
    if (!class_exists($class)) {
        include_once $path . 'class.' . $class . '.php';
    }
    if (!class_exists($class)) {
        return false;
    }
    $obj = new $class($db);
    return $obj;
    unset($db);
}
function editor2html($str, $topicid){
    global $db;
	//匹配本地图片
    preg_match_all('/\[(photo)=(\d+)\]/is', $str, $photos);
    foreach ($photos[2] as $item) {
        $strPhoto = aac('photo')->getPhotoForApp($item);
        $str = str_replace("[photo={$item}]", '<a href="' . SITE_URL . 'go/url/goid-' .
            $topicid . '" target="_blank">
							<img class="thumbnail" src="' . SITE_URL . miniimg($strPhoto['photourl'],
            'photo', '500', '500', $strPhoto['path']) . '" title="查看购买信息" /></a>', $str);
    }
	//匹配附件
    preg_match_all('/\[(attach)=(\d+)\]/is', $str, $attachs);
    if ($attachs[2]) {
        foreach ($attachs[2] as $aitem) {
            $strAttach = aac('attach')->getOneAttach($aitem);
            if ($strAttach['isattach'] == '1') {
                $str = str_replace("[attach={$aitem}]", '<span class="attach_down">附件下载：
									 <a href="' . SITE_URL .
                    'index.php?app=attach&ac=ajax&ts=down&attachid=' . $aitem . '" target="_blank">' .
                    $strAttach["attachname"] . '</a></span>', $str);
            } else {
                $str = str_replace("[attach={$aitem}]", '', $str);
            }
        }
    }
    $find = array("http://", "-", '.', "/", '?', '=', '&');
    $replace = array("", '_', '', '', '', '', '');
    preg_match_all('/\[(video)=(.*?)\]/is', $str, $video);
    if ($video[2]) {
        foreach ($video[2] as $aitem) {
            $arr = explode(',', $aitem);
            $id = str_replace($find, $replace, $arr[0]);
            $html = '<div id="img_' . $id .
                '"><a href="javascript:void(0)" onclick="showVideo(\'' . $id . '\',\'' . $arr[1] .
                '\');"><img src="' . $arr[0] . '"/></a></div>';
            $html .= '<div id="play_' . $id . '" style="display:none">' . $arr['2'] .
                ' <a href="javascript:void(0)" onclick="showVideo(\'' . $id . '\',\'' . $arr[1] .
                '\');">收起</a>
			<div id="swf_' . $id . '"></div> </div>';
            $str = str_replace("[video={$aitem}]", $html, $str);
        }
    }
    preg_match_all('/\[(mp3)=(.*?)\]/is', $str, $music);
    if ($music[2]) {
        foreach ($music[2] as $aitem) {
            $arr = explode(',', $aitem);
            $id = str_replace($find, $replace, $arr[0]);
            $mp3flash = '<div id="mp3swf_' . $id . '" class="mp3player">
			<div>' . $arr[1] . ' <a href="' . $aitem . '" target="_blank">下载</a> </div>
			<object height="24" width="290" data="' . SITE_URL .
                'public/flash/player.swf" type="application/x-shockwave-flash">
				<param value="' . SITE_URL . 'public/flash/player.swf" name="movie"/>
				<param value="autostart=no&bg=0xCDDFF3&leftbg=0x357DCE&lefticon=0xF2F2F2&rightbg=0xF06A51&rightbghover=0xAF2910&righticon=0xF2F2F2&righticonhover=0xFFFFFF&text=0x357DCE&slider=0x357DCE&track=0xFFFFFF&border=0xFFFFFF&loader=0xAF2910&soundFile=' .
                $aitem . '" name="FlashVars"/>
				<param value="high" name="quality"/>
				<param value="false" name="menu"/>
				<param value="#FFFFFF" name="bgcolor"/>
				</object></div>';
            $str = str_replace("[mp3={$aitem}]", $mp3flash, $str);
        }
    }
    return $str;
    unset($db);
}
function qiMsg($msg, $button = '点击返回>>', $url = 'javascript:history.back(-1);',$isAutoGo = false){
    echo "<html>
	<head>";
    if ($isAutoGo) {
        echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\" />";
    }
    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>提示</title>
<style type=\"text/css\">
<!--
body {
background-color:#EDEDED;
font-family: Arial;
font-size: 12px;
line-height:150%;
text-align:center;
}
a{color:#555555;}
.main {
width:500px;
background-color:#FFFFFF;
font-size: 12px;
color: #666666;
margin:100px auto 0;
list-style:none;
padding:20px;
}
.main p {
line-height: 18px;
margin: 5px 20px;
font-size:14px;
}
-->
</style>
</head>
<body>
<div class=\"main\">
<p>$msg</p>
<p><a href=\"$url\">$button</a></p>
</div>
</body>
</html>";
    exit;
}
function pagination($count, $perlogs, $page, $url, $suffix = ''){
    $pnums = @ceil($count / $perlogs);
    $re = '';
    for ($i = $page - 5; $i <= $page + 5 && $i <= $pnums; $i++) {
        if ($i > 0) {
            if ($i == $page) {
                $re .= ' <span class="current">' . $i . '</span> ';
            } else {
                $re .= '<a href="' . $url . $i . $suffix . '">' . $i . '</a>';
            }
        }
    }
    if ($page > 6)
        $re = '<a href="' . $url . '1' . $suffix . '" title="首页">?</a> ...' . $re;
    if ($page + 5 < $pnums)
        $re .= '... <a href="' . $url . $pnums . $suffix . '" title="尾页">?</a>';
    if ($pnums <= 1)
        $re = '';
    return $re;
}

function paginationv($count, $perlogs, $page, $url, $suffix = ''){
    $pnums = @ceil($count / $perlogs);
    $re = '';
    for ($i = $page - 5; $i <= $page + 5 && $i <= $pnums; $i++) {
        if ($i > 0) {
            if ($i == $page) {
                $re .= ' <span class="current">' . $i . '</span> ';
            } else {
                $re .= '<a href="/talk/' . $url . $i . $suffix . '">' . $i . '</a>';
            }
        }
    }
    if ($page > 6)
        $re = '<a href="/talk/' . $url . '1' . $suffix . '" title="首页">?</a> ...' . $re;
    if ($page + 5 < $pnums)
        $re .= '... <a href="/talk/' . $url . $pnums . $suffix . '" title="尾页">?</a>';
    if ($pnums <= 1)
        $re = '';
    return $re;
}

function valid_email($email){
    if (!@ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
        return false;
    }
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!@ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
            $local_array[$i])) {
            return false;
        }
    }
    if (!@ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false;
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!@ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",
                $domain_array[$i])) {
                return false;
            }
        }
    }
    return true;
}

function getTime($btime, $etime){
    if ($btime < $etime) {
        $stime = $btime;
        $endtime = $etime;
    } else {
        $stime = $etime;
        $endtime = $btime;
    }
    $timec = $endtime - $stime;
    $days = intval($timec / 86400);
    $rtime = $timec % 86400;
    $hours = intval($rtime / 3600);
    $rtime = $rtime % 3600;
    $mins = intval($rtime / 60);
    $secs = $rtime % 60;
    if ($days >= 1) {
        return $days . ' 天前';
    }
    if ($hours >= 1) {
        return $hours . ' 小时前';
    }
    if ($mins >= 1) {
        return $mins . ' 分钟前';
    }
    if ($secs >= 1) {
        return $secs . ' 秒前';
    }
}

function getIp(){
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $PHP_IP = getenv('HTTP_CLIENT_IP');
    } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),
    'unknown')) {
        $PHP_IP = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $PHP_IP = getenv('REMOTE_ADDR');
    } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp
    ($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $PHP_IP = $_SERVER['REMOTE_ADDR'];
    }
    preg_match("/[\d\.]{7,15}/", $PHP_IP, $ipmatches);
    $PHP_IP = $ipmatches[0] ? $ipmatches[0] : 'unknown';
    return $PHP_IP;
}

function cleanJs($text){
    $text = trim($text);
    $text = stripslashes($text);
    $text = preg_replace('/<!--?.*-->/', '', $text);
    $text = preg_replace('/<\?|\?>/', '', $text);
    $text = preg_replace('/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i', '', $text);
    while (preg_match('/(<[^><]+)(lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i',$text, $mat)) {
        $text = str_replace($mat[0], $mat[1], $text);
    }
    while (preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat)) {
        $text = str_replace($mat[0], $mat[1] . $mat[3], $text);
    }
    return $text;
}

function t($text){
    $text = cleanJs($text);
    $text = preg_replace('/\s(?=\s)/', '', $text);
    $text = preg_replace('/[\n\r\t]/', ' ', $text);
    $text = str_replace('  ', ' ', $text);
    $text = str_replace(' ', '', $text);
    $text = str_replace('?', '', $text);
/*
    $text = str_replace('&nbsp;', '', $text);
    $text = str_replace('&', '', $text);
    $text = str_replace('=', '', $text);
    $text = str_replace('-', '', $text);
    $text = str_replace('#', '', $text);
    $text = str_replace('%', '', $text);
    $text = str_replace('!', '', $text);
    $text = str_replace('@', '', $text);
    $text = str_replace('^', '', $text);
    $text = str_replace('*', '', $text);
    $text = str_replace('amp;', '', $text);
*/
    $text = strip_tags($text);
    $text = htmlspecialchars($text);
    $text = str_replace("'", "''", $text);
    return $text;
}

function h($text){
    $text = trim($text);
    $text = htmlspecialchars($text);
    $text = addslashes($text);
    return $text;
}

function hview($text){
    $text = stripslashes($text);
    $text = nl2br($text);
    return $text;
}

/*
$serurl = $_SERVER['HTTP_HOST'];
$params = "serurl=$serurl";
$serreturn = http_request('http://www.letutao.com/index.php?app=group&ac=notice',
    'POST', $params);
$serreturnst = $serreturn[0];
if (empty($serreturnst)) {
    qiMsg('请确保您的网络连接没有问题！');
}
if ($GLOBALS['IIIIIIIII1Il']($serreturnst, 'yes')) {
} else {
    qiMsg('该软件未授权', '点击授权', 'http://www.letutao.com');
}
*/

function mb_unserialize($serial_str){
    $serial_str = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'",
        $serial_str);
    $serial_str = str_replace("\r", "", $serial_str);
    return unserialize($serial_str);
}

function asc_unserialize($serial_str){
    $serial_str = preg_replace('!s:(\d+):"(.*?)";!se',
        '"s:".strlen("$2").":\"$2\";"', $serial_str);
    $serial_str = str_replace("\r", "", $serial_str);
    return unserialize($serial_str);
}

function getsubstrutf8($string, $start = 0, $sublen, $append = true){
    $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
    preg_match_all($pa, $string, $t_string);
    if (count($t_string[0]) - $start > $sublen && $append == true) {
        return join('', array_slice($t_string[0], $start,
            $sublen)) . "...";
    } else {
        return join('', array_slice($t_string[0], $start,
            $sublen));
    }
}

function dirList($dir, $bool = "dirs"){
    $truedir = $dir;
    $dir = scandir($dir);
    if ($bool == "files") {
        $direct = 'is_dir';
    } elseif ($bool == "dirs") {
        $direct = 'is_file';
    }
    foreach ($dir as $k => $v) {
        if (($direct($truedir . '/' . $dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ||
            $dir[$k] == '.svn') {
            unset($dir[$k]);
        }
    }
    $dir = array_values($dir);
    return $dir;
}

function getmicrotime(){
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function AppFileWrite($arrData, $app, $file){
    $appDir = 'app/' . $app;
    !is_dir($appDir) ? mkdir($appDir,0777) : '';
    $appFile = $appDir . '/' . $file;
    if ($appFile){
        unlink($appFile);
	}
    @$fp = fopen($appFile, 'a') or qiMsg('读取文件失败。如果您使用的是Unix/Linux主机，请修改app目录 (app/'.$app.') 下所有文件的权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
    $arrData = "<?php\ndefined('IN_TS') or die('Access Denied.');\nreturn ".var_export($arrData, true).";\n?>";
    @$fw = fwrite($fp, $arrData) or qiMsg('写入文件失败，目录 (app/'.$app.') 不可写');
    fclose($fp);
}

function AppCacheWrite($cacheData, $app, $cacheFile){
    $appFile = THINKDATA . '/cache/' . $app;
    !is_dir($appFile) ? mkdir($appFile,0777) : '';
    $cacheFile = $appFile . '/' . $cacheFile;
    if ($cacheFile){
        unlink($cacheFile);
	}
    @$fp = fopen($cacheFile, 'a') or qiMsg('读取缓存失败。如果您使用的是Unix/Linux主机，请修改缓存目录 (data/cache/'.$app.') 下所有文件的权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
    $cacheData = "<?php\nreturn " . var_export($cacheData, true) . ";\n?>";
    @$fw = fwrite($fp, $cacheData) or qiMsg('写入缓存失败，缓存目录 (data/cache/'.$app.') 不可写');
    fclose($fp);
}

function AppCacheRead($app, $cacheFile){
    $arrData = require_once THINKDATA .'/cache/'.$app.'/'.$cacheFile;
    return $arrData;
}

function PluginCacheWrite($cacheData, $app, $plugin, $cacheFile){
    $appFile = 'plugins/' . $app . '/' . $plugin;
    !is_dir($appFile) ? mkdir($appFile) : '';
    $cacheFile = $appFile . '/' . $cacheFile;
    if ($cacheFile){
        unlink($cacheFile);
	}
    @$fp = fopen($cacheFile, 'a') or qiMsg('读取缓存失败。如果您使用的是Unix/Linux主机，请修改缓存目录 (plugins/' .$app.'/'.$plugin.'/'.$cacheFile.')  权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
    $cacheData = "<?php\nreturn " . var_export($cacheData, true) . ";\n?>";
    @$fw = fwrite($fp, $cacheData) or qiMsg('写入缓存失败，缓存目录 (plugins/' .$app.'/'.$plugin.'/'.$cacheFile.') 不可写');
    fclose($fp);
}

function PluginCacheRead($app, $plugin, $cacheFile){
    $cacheData = require_once 'plugins/'.$app.'/'.$plugin.'/'.$cacheFile;
    return $cacheData;
}

function array_to_str($arr){
    $str = '';
    $count = 1;
    if (is_array($arr)) {
        foreach ($arr as $a) {
            if ($count == 1) {
                $str .= $a;
            } else {
                $str.= ','.$a;
            }
            $count++;
        }
    }
    return $str;
}

function random($length, $numeric = 0){
    PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
    $seed = base_convert(md5(print_r($_SERVER, 1) . microtime()), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed).'012340567890'):($seed.'zZ'. strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed[mt_rand(0, $max)];
    }
    return $hash;
}

function getHtmlByCurl($url, $proxy, $timeout){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    return $file_contents;
}

function format_bytes($size){
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++)
        $size /= 1024;
    return round($size, 2).$units[$i];
}

function is_wap(){
    $http_via = isset($_SERVER['HTTP_VIA']) ? strtolower($_SERVER['HTTP_VIA']) : '';
    return !empty($http_via) && strstr($http_via, 'wap') ? 1 : 0;
}

function object_array($array){
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function isWriteFile($file, $content, $mod = 'w', $exit = true){
    if (!@$fp = @fopen($file, $mod)) {
        if ($exit) {
            exit('File :<br>' . $file . '<br>Have no access to write!');
        } else {
            return false;
        }
    } else {
        @flock($fp, 2);
        @fwrite($fp, $content);
		@fclose($fp);
        return true;
    }
}

function MooMakeDir($dir){
    return is_dir($dir) or (MooMakeDir(dirname($dir)) and  mkdir($dir, 0777));
}

function template($file){
    global $app;
    $tplfile = 'app/'.$app.'/html/'.$file.'.html';
    $objfile = 'cache/template/' . $app . '.' . $file . '.tpl.php';
    if (@filemtime($tplfile) > @filemtime($objfile)) {
        require_once 'letutao/class.template.php';
        $T = new template();
        $T->complie($tplfile, $objfile);
    }
    return $objfile;
    unset($app);
}

function pubTemplate($file){
    $tplfile = 'public/html/'.$file.'.html';
    $objfile = 'cache/template/public.'.$file.'.tpl.php';
    if (@filemtime($tplfile) > @filemtime($objfile)) {
        require_once 'letutao/class.template.php';
        $T = new template();
        $T->complie($tplfile, $objfile);
    }
    return $objfile;
}

function addAction($hook, $actionFunc){
    global $tsHooks;
    if (!@in_array($actionFunc, $tsHooks[$hook])) {
        $tsHooks[$hook][] = $actionFunc;
    }
    return true;
}

function doAction($hook){
    global $tsHooks;
    $args = array_slice(func_get_args(), 1);
    if (isset($tsHooks[$hook])) {
        foreach ($tsHooks[$hook] as $function) {
            $string = call_user_func_array($function, $args);
        }
    }
}

function createFolders($path){
    if (!file_exists($path)) {
        createFolders(dirname($path));
        mkdir($path, 0777);
    }
}

function delDir($dir = ''){
    if (empty($dir)) {
        $dir = rtrim(RUNTIME_PATH, '/');
    }
    if (substr($dir, -1) == '/') {
        $dir = rtrim($dir, '/');
    }
    if (!file_exists($dir))
        return true;
    if (!is_dir($dir) || is_link($dir))
        return @unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..')
            continue;
        if (!delDir($dir . "/" . $item)) {
            @$chmod($dir . "/" . $item, 0777);
            if (!delDir($dir . "/" . $item))
            return false;
        }
        ;
    }
    return @rmdir($dir);
}

function getHttpUrl(){
    $arrUri = explode('index.php', $_SERVER['REQUEST_URI']);
    $site_url = 'http://'.$_SERVER['HTTP_HOST'].$arrUri[0];
    return $site_url;
}

function md10($str = ''){
    return substr(md5($str), 10, 10);
}

function miniimg($file, $app, $w, $h, $path = '', $c = '0'){
    if (!$file) {
        return;
    }
    $info = explode('.', $file);
    $name = md10($file).'_'.$w.'_'.$h.'.'.$info[1];
    if ($path == '') {
        $cpath = 'cache/' . $app . '/' . $w . '/' . $name;
    } else {
        $cpath = 'cache/' . $app . '/' . $path . '/' . $w . '/' . $name;
    }
    if (!is_file($cpath)) {
        createFolders('cache/' . $app . '/' . $path . '/' . $w);
        $dest = 'uploadfile/' . $app . '/' . $file;
        $arrImg = getimagesize($dest);
        if ($arrImg[0] <= $w) {
            copy($dest, $cpath);
        } else {
            require_once 'letutao/class.image.php';
            $resizeimage = new tsImg("$dest", $w, $h, $c, "$cpath");
        }
    }
    return $cpath;
}
function ob_gzip($content){
    if (!headers_sent() && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")) {
        $content = gzencode($content, 9);
        header("Content-Encoding: gzip");
        header("Vary: Accept-Encoding");
        header("Content-Length: ".strlen($content));
    }
    return $content;
}

function tsurl($app, $ac = '', $params = array()){
    $options = include 'data/cache/system/options.php';
    $urlset = $options['site_urltype'];
    if ($urlset == 1) {
        foreach ($params as $k => $v) {
            $str .= '&' . $k . '=' . $v;
        }
        if ($ac == '') {
            $ac = '';
        } else {
            $ac = '&ac=' . $ac;
        }
        $url = 'index.php?app=' . $app . $ac . $str;
    } elseif ($urlset == 2) {
        foreach ($params as $k => $v) {
            $str .= '/' . $k . '-' . $v;
        }
        if ($ac == '') {
            $ac = '';
        } else {
            $ac = '/' . $ac;
        }
        $url = 'index.php/' . $app . $ac . $str;
    } elseif ($urlset == 3) {
        foreach ($params as $k => $v) {
            $str .= '-' . $k . '-' . $v;
        }
        $url = $app . '-' . $ac . $str . '.html';
    } elseif ($urlset == 4) {
        foreach ($params as $k => $v) {
            $str .= '/' . $k . '-' . $v;
        }
        if ($ac == '') {
            $ac = '';
        } else {
            $ac = '/' . $ac;
        }
        $url = $app . $ac . $str;
    }
    return $url;
}

function reurl(){
    $scriptName = explode('index.php', $_SERVER['SCRIPT_NAME']);
    $rurl = substr($_SERVER['REQUEST_URI'], strlen($scriptName[0]));
    if (strpos($rurl, '?') == false) {
        if (preg_match('/index.php/i', $rurl)) {
            $rurl = str_replace('index.php', '', $rurl);
            $rurl = substr($rurl, 1);
            $params = $rurl;
        } else {
            $params = $rurl;
        }
        if ($rurl) {
            $params = explode('/', $params);
            foreach ($params as $p => $v) {
                switch ($p) {
                    case 0:
                        $_GET['app'] = $v;
                        break;
                    case 1:
                        $_GET['ac'] = $v;
                        break;
                    default:
                        $kv = explode('-', $v);
                        if (count($kv) > 1) {
                            $_GET[$kv[0]] = $kv[1];
                        } else {
                            $_GET['params' . $p] = $kv[0];
                        }
                        break;
                }
            }
        }
    }
}

function iswriteable($file){
    if (is_dir($file)) {
        $dir = $file;
        if ($fp = @fopen("$dir/test.txt", 'w')) {
            @fclose($fp);
            @unlink("$dir/test.txt");
            $writeable = 1;
        } else {
            $writeable = 0;
        }
    } else {
        if ($fp = @fopen($file, 'a+')) {
            @fclose($fp);
            $writeable = 1;
        } else {
            $writeable = 0;
        }
    }
    return $writeable;
}

function delDirFile($dir){
    $arrFiles = dirList($dir, 'files');
    foreach ($arrFiles as $item) {
        unlink($dir . '/' . $item);
    }
}

function getPhotoById($photoid){
    global $DB;
    $strPhoto = aac('photo', $db)->getPhotoForApp($photoid);
    return SITE_URL . "uploadfile/photo/" . $strPhoto['photourl'];
}

//执行HTTP请求
function http_request($url, $method = 'GET', $data = '', $cookie = '', $refer = ''){
    $header = '';
    $body = '';
    $newcookie = '';
    if (preg_match('/^http:\/\/(.*?)(\/.*)$/', $url, $reg)) {
        $host = $reg[1];
        $path = $reg[2];
    } else {
        outs(1, "URL($url)格式非法!");
        return;
    }
    $http_host = $host;
    if (preg_match('/^(.*):(\d+)$/', $host, $reg)) {
        $host = $reg[1];
        $port = $reg[2];
    } else
        $port = 80;
    $fp = fsockopen($host, $port, $errno, $errstr, 30);
    if (!$fp) {
        outs(1, "$errstr ($errno)\n");
    } else {
        fputs($fp, "$method $path HTTP/1.1\r\n");
        fputs($fp, "Host: $http_host\r\n");
        if ($refer != '')
            fputs($fp, "Referer: $refer\r\n");
        if ($cookie != '')
            fputs($fp, "Cookie: $cookie\r\n");
        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: " . strlen($data) . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data . "\r\n\r\n");
        $header_body = 0;
        $chunked_format = 0;
        $chunked_len = 0;
        while (!feof($fp)) {
            $str = fgets($fp);
            //$len=hexdec($str);        if ($header_body==1) {echo ">>$str\t$len\n";        $str=fread($fp,$len);echo $str;}
            if ($header_body == 1) {
                if ($chunked_format) {
                    if ($chunked_len <= 0) {
                        $chunked_len = hexdec($str);
                        if ($chunked_len == 0)
                            break;
                        else
                            continue;
                    } else {
                        $chunked_len -= strlen($str);
                        if ($chunked_len <= 0)
                            $str = trim($str);
                        //elseif ($chunked_len==0) fgets($fp);
                    }
                }
                $body .= $str;
            } else
                if ($str == "\r\n")
                    $header_body = 1;
                else {
                    $header .= $str;
                    if ($str == "Transfer-Encoding: chunked\r\n")
                        $chunked_format = 1;
                    if (preg_match('|Set-Cookie: (\S+)=(\S+);|', $str, $reg))
                        $newcookie .= ($newcookie == '' ? '' : '; ') . $reg[1] . '=' . $reg[2];
                }
        }
        fclose($fp);
    }
    $GLOBALS['TRAFFIC'] += 414 + strlen($url) + strlen($data) + strlen($header) + strlen($body);
    if (preg_match('/^Location: (\S+)\r\n/m', $header, $reg)) {
        if (substr($reg[1], 0, 1) != '/') {
            $path = substr($path, 0, strrpos($path, '/') + 1);
            $path .= $reg[1];
        } else
            $path = $reg[1];
        if ($newcookie)
            $cookie = $newcookie;
        return http_request('http://' . $http_host . $path, 'GET', '', $cookie, $url);
    }
    return array($body, $header, $newcookie);
}